﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Utility;
using VAdvantage.Classes;
using System.Data;
using VAdvantage.Model;
using System.Collections;
using System.Threading;
using VAdvantage.DataBase;

namespace VAdvantage.Framework
{
    public partial class MailFormat : ChildWindow
    {
        private SLControls.Controls.VDataGrid vdgv = new SLControls.Controls.VDataGrid();
        int _AD_Window_ID = 0;
        private List<int?> _results = new List<int?>(3);

        public MailFormat()
        {
            InitializeComponent();
            LayoutRoot.Background = new SolidColorBrush(DataBase.GlobalVariable.WINDOW_BACK_COLOR);
            this.vdgv.HorizontalAlignment = HorizontalAlignment.Stretch;
            this.vdgv.VerticalAlignment = VerticalAlignment.Stretch;
            vdgv.KeyDown += new KeyEventHandler(vdgv_KeyDown);
            vdgv.SelectionChanged += new SelectionChangedEventHandler(vdgv_SelectionChanged);
        }

        public MailFormat(int AD_Window_ID, bool isEmail,DataSet ds)
            : this()
        {
            this.Width = 700;
            this.Height = 500;
            _AD_Window_ID = AD_Window_ID;
            SetGrid(ds);
            this.Title = Msg.GetMsg(Envs.GetCtx(), isEmail ? "MailFormat" : "LetterFormat");
        }

        void vdgv_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //if (e.RowIndex == -1)
            //    return;
            //IList rowSource = vdgv.ItemsSource as IList;
            //int row = -1;
            //try
            //{
            //    //row = vdgv.SelectedRows[0].Index;
            //    row = vdgv.SelectedIndex;
            //}
            //catch { }
            //System.Threading.ThreadPool.QueueUserWorkItem(delegate
            //{
            //    int? data = GetSelectedRowKey(rowSource, row);
            //    if (data != null)
            //    {
            //        _results.Add(data);
            //    }
            //    Dispatcher.BeginInvoke(delegate
            //    {
            //        hasdata = true;
            //        //vdgv.Columns.Clear();
            //        vdgv = null;
            //        //this.DialogResult = true;
            //    });
            //});
        }

        void vdgv_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                vbtnOk_Click(sender, e);
            }
        }

        DataSet ds = new DataSet();


        bool hasdata = false;

        public bool HasData()
        {
            return hasdata;
        }

        ////this.vdgv.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.vdgv_MouseDoubleClick);
        ////this.vdgv.CellDoubleClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.vdgv_CellDoubleClick);
        ////this.vdgv.CellMouseDoubleClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.vdgv_CellMouseDoubleClick);
        //this.vdgv.KeyDown += new KeyEventHandler(vdgv_KeyDown);

        public void SetGrid(DataSet ds)
        {

            vdgv.Columns.Clear();
            vdgv.AutoGenerateColumns = false;
            this.vdgv.ColumnWidth = new DataGridLength(0, DataGridLengthUnitType.Auto);
            this.vdgv.RowHeight = 35;
            vdgv.HorizontalAlignment = HorizontalAlignment.Stretch;
            this.vdgv.ShowRowNumber = true;
            vdgv.VerticalAlignment = VerticalAlignment.Stretch;
            //this.vdgv.Dock = System.Windows.Forms.DockStyle.Fill;
            //this.vdgv.Location = new System.Drawing.Point(3, 3);
            this.vdgv.Name = "vdgv";
            //this.vdgv.Size = new System.Drawing.Size(795, 423);
            this.vdgv.TabIndex = 4;
            // CommonFunctions.SetDataGridPrperties(vdgv);
            vdgv.IsReadOnly = true;
            DataGridTextColumn name = new DataGridTextColumn();
            name.Header = Msg.Translate(Envs.GetContext(), "Name");
            name.Binding = new System.Windows.Data.Binding("NAME");
            name.IsReadOnly = true;
            vdgv.Columns.Add(name);
            DataGridTextColumn subject = new DataGridTextColumn();
            subject.Header = Msg.Translate(Envs.GetContext(), "Subject");
            subject.Binding = new System.Windows.Data.Binding("SUBJECT");
            subject.IsReadOnly = true;
            vdgv.Columns.Add(subject);
            DataGridTextColumn mailtext = new DataGridTextColumn();
            mailtext.Header = Msg.Translate(Envs.GetContext(), "Mailtext");
            mailtext.Binding = new System.Windows.Data.Binding("MAILTEXT");
            mailtext.IsReadOnly = true;
            vdgv.Columns.Add(mailtext);
            DataGridTextColumn created = new DataGridTextColumn();
            created.Header = Msg.Translate(Envs.GetContext(), "Created");
            created.Binding = new System.Windows.Data.Binding("CREATED");
            created.IsReadOnly = true;
            vdgv.Columns.Add(created);
            DataGridTextColumn ad_client_id = new DataGridTextColumn();
            ad_client_id.Header = Msg.Translate(Envs.GetContext(), "AD_Client_ID");
            ad_client_id.Binding = new System.Windows.Data.Binding("AD_CLIENT_ID");
            ad_client_id.IsReadOnly = true;
            ad_client_id.Visibility = Visibility.Collapsed;
            vdgv.Columns.Add(ad_client_id);
            DataGridTextColumn ad_org_id = new DataGridTextColumn();
            ad_org_id.Header = Msg.Translate(Envs.GetContext(), "AD_Org_ID");
            ad_org_id.Binding = new System.Windows.Data.Binding("AD_ORG_ID");
            ad_org_id.Visibility = Visibility.Collapsed;
            ad_org_id.IsReadOnly = true;
            vdgv.Columns.Add(ad_org_id);
            DataGridTextColumn createdby = new DataGridTextColumn();
            createdby.Header = Msg.Translate(Envs.GetContext(), "CreatedBy");
            createdby.Binding = new System.Windows.Data.Binding("CREATEDBY");
            createdby.Visibility = Visibility.Collapsed;
            createdby.IsReadOnly = true;
            vdgv.Columns.Add(createdby);
            DataGridTextColumn isactive = new DataGridTextColumn();
            isactive.Header = Msg.Translate(Envs.GetContext(), "IsActive");
            isactive.Binding = new System.Windows.Data.Binding("ISACTIVE");
            isactive.IsReadOnly = true;
            isactive.Visibility = Visibility.Collapsed;
            vdgv.Columns.Add(isactive);
            DataGridTextColumn ishtml = new DataGridTextColumn();
            ishtml.Header = Msg.Translate(Envs.GetContext(), "IsHtml");
            ishtml.Binding = new System.Windows.Data.Binding("ISHTML");
            ishtml.Visibility = Visibility.Collapsed;
            ishtml.IsReadOnly = true;
            vdgv.Columns.Add(ishtml);
            DataGridTextColumn ad_texttemplate_id = new DataGridTextColumn();
            ad_texttemplate_id.Header = Msg.Translate(Envs.GetContext(), "AD_TextTemplate_ID");
            ad_texttemplate_id.Binding = new System.Windows.Data.Binding("AD_TEXTTEMPLATE_ID");
            ad_texttemplate_id.IsReadOnly = true;
            ad_texttemplate_id.Visibility = Visibility.Collapsed;
            vdgv.Columns.Add(ad_texttemplate_id);
            DataGridTextColumn updated = new DataGridTextColumn();
            updated.Header = Msg.Translate(Envs.GetContext(), "Updated");
            updated.Binding = new System.Windows.Data.Binding("UPDATED");
            updated.Visibility = Visibility.Collapsed;
            updated.IsReadOnly = true;
            vdgv.Columns.Add(updated);
            DataGridTextColumn updatedby = new DataGridTextColumn();
            updatedby.Header = Msg.Translate(Envs.GetContext(), "UpdatedBy");
            updatedby.Binding = new System.Windows.Data.Binding("UPDATEDBY");
            updatedby.Visibility = Visibility.Collapsed;
            updatedby.IsReadOnly = true;
            vdgv.Columns.Add(updatedby);
            DataGridTextColumn isdynamiccontent = new DataGridTextColumn();
            isdynamiccontent.Header = Msg.Translate(Envs.GetContext(), "IsDynamicContent");
            isdynamiccontent.Binding = new System.Windows.Data.Binding("ISDYNAMICCONTENT");
            isdynamiccontent.IsReadOnly = true;
            vdgv.Columns.Add(isdynamiccontent);



            LayoutRoot.Children.Add(vdgv);

            if (ds != null)
            {
                vdgv.ItemsSource = ds.Tables[0].GetBindableData(new Connector());
            }
            else
            {
                vdgv.ItemsSource = null;
            }
            hasdata = true;

        }

        private object _name, _msg, _sub, _id, _isDynamic;

        public Object Subject
        {
            get
            {
                return _sub;
            }
            set
            {
                _sub = value;
            }
        }

        public Object Message
        {
            get
            {
                return _msg;
            }
            set
            {
                _msg = value;
            }
        }

        public Object FileName
        {
            get
            {
                return _name;
            }
            set
            {
                _name = value;
            }

        }

        public Object Id
        {
            get
            {
                return _id;
            }

            set
            {
                _id = value;
            }
        }

        public Object IsDynamic
        {
            get
            {
                return _isDynamic;
            }
            set
            {
                _isDynamic = value;
            }
        }

        private Dictionary<string, byte[]> _attachment = new Dictionary<string, byte[]>();

        public Dictionary<string, byte[]> Attachments
        {
            get
            {
                return _attachment;
            }
            set
            {
                _attachment = value;
            }
        }



        private void vbtnOk_Click(object sender, RoutedEventArgs e)
        {
            hasdata = false;
            
            IList rowSource = vdgv.ItemsSource as IList;
            int row = -1;
            try
            {
                //row = vdgv.SelectedRows[0].Index;
               row = vdgv.SelectedIndex;
            }
            catch { }
            if (row == -1)
            {
                return;
            }
            vbtnOk.IsEnabled = false;
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {

                int? data = GetSelectedRowKey(rowSource, row);
                if (data != null)
                {
                    _results.Add(data);
                }
                Dispatcher.BeginInvoke(delegate
                {
                    hasdata = false;
                    vdgv = null;
                    this.DialogResult = true;
                });
            });
        }

        private void vbtnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        /// <summary>
        /// Gets the selected row key from data grid view.
        /// </summary>
        /// <returns></returns>

        protected int? GetSelectedRowKey(IList rowSource, int row)
        {
            
            
            //if (row != -1 && _keyColumnIndex != -1)
            if (row >= 0)
            {
             

                Object data = ((BindableObject)rowSource[row]).GetValue("ad_texttemplate_id").ToString();
                Id = ((BindableObject)rowSource[row]).GetValue("ad_texttemplate_id").ToString();
                Subject = ((BindableObject)rowSource[row]).GetValue("subject").ToString();
                Message = ((BindableObject)rowSource[row]).GetValue("mailtext").ToString();
                FileName = ((BindableObject)rowSource[row]).GetValue("name").ToString();
                IsDynamic = ((BindableObject)rowSource[row]).GetValue("IsDynamicContent").ToString();

                String sql = "Select AD_Table_ID from AD_Table where tablename='AD_TextTemplate'";
                int ad_table_ID =Convert.ToInt32(VAdvantage.DataBase.DB.ExecuteScalar(sql));

                MMailAttachment1 _mattchment=null;
                sql = "select mailattachment1_id from MailAttachment1 where ad_table_id=" + ad_table_ID + " and record_id=" + Convert.ToInt32(Id);
                object mailAttachmentID = DB.ExecuteScalar(sql);
                if (mailAttachmentID == null && mailAttachmentID == DBNull.Value)
                {
                    _mattchment = new MMailAttachment1(Envs.GetCtx(), 0, null);
                }
                else
                {
                    _mattchment = new MMailAttachment1(Envs.GetCtx(), Convert.ToInt32(mailAttachmentID), null);
                }

                 //= new MMailAttachment1(Envs.GetCtx(),ad_table_ID,Convert.ToInt32(Id), null);
                MAttachmentEntry[] entry= _mattchment.GetEntries();
                for(int i=0;i<entry.Count();i++)
                {
                    _attachment[entry[i].GetName()] = entry[i].GetData();
                }
                Attachments = _attachment;



                if (data.GetType() == typeof(IDColumn))
                {
                    data = ((IDColumn)data).GetRecord_ID();
                    return (int)data;
                }
                else if (data.GetType() == typeof(int))
                {
                    return (int)data;
                }
                else if (data.GetType() == typeof(Decimal))
                {
                    return System.Convert.ToInt32(data);
                }

            }


            return null;
        }
    }
}

